package controllers.user;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import play.db.jpa.JPABase;
import play.mvc.Before;
import play.mvc.Http.Header;
import play.mvc.With;

import com.pany.domain.IConstant;
import com.pany.domain.IConstant.IDictType;
import com.pany.domain.IConstant.ISysConstant;
import com.pany.domain.IConstant.IUserResultCode;
import com.pany.domain.models.User;
import com.pany.domain.models.VIPInfo;
import com.pany.domain.req.CreateVipReq;
import com.pany.domain.req.GetMemberListReq;
import com.pany.domain.req.GetUserListReq;
import com.pany.domain.req.LoginRequest;
import com.pany.domain.rsp.CreateVipRsp;
import com.pany.domain.rsp.GetMemberListRsp;
import com.pany.domain.rsp.GetUserListRsp;
import com.pany.domain.rsp.LoginResponse;
import com.pany.utils.DictUtils;
import com.pany.utils.ServiceUtils;
import com.pany.utils.SessionUtil;
import com.pany.utils.UUIDGenerator;

import controllers.BaseController;
import controllers.interceptor.UserSecure;

import com.pany.domain.IConstant;
import com.pany.exceptions.ServiceException;

@With(UserSecure.class)
public class UserController extends BaseController
{
    
    /**
     * 操作登陆
     */
    public static void login()
    {
        LoginRequest req = readObject(LoginRequest.class);
        User user = User.find("from User where userName=? and passwd=?", req.getUserName(), req.getPasswd()).first();
        LoginResponse rsp = new LoginResponse();
        rsp.setUser(user);
        if (user != null)
        {
            if (IConstant.USER_TYPE_CUSTOMER.equals(user.getUserType()))
            {
                throw new ServiceException(IUserResultCode.LOGIN_FAIL_UNAME_PWD_UNMATCH);
            }
            user.setPasswd(null);
            
            String sid = SessionUtil.addSession();
            SessionUtil.addAttr(sid, IConstant.ISysConstant.USER_SESSION_KEY, user);
            setUserDict(user);
            
            rsp.setSid(sid);
            renderSuccess(rsp);
        }
        else
        {
            throw new ServiceException(IUserResultCode.LOGIN_FAIL_UNAME_PWD_UNMATCH);
        }
    }
    
    /**
     * 获取普通用户列表
     */
    public static void getUserList()
    {
        GetUserListReq req = readObject(GetUserListReq.class);
        GetUserListRsp rsp = new GetUserListRsp();
        rsp.setTotalNum(ServiceUtils.queryCountByCondition(req));
        if (rsp.getTotalNum() > 0)
        {
            List<User> list = (ServiceUtils.queryByCondition(req, User.class, "userId", "userName", "age", "sex"));
            if (CollectionUtils.isNotEmpty(list))
            {
                rsp.setUsers(list);
                for (User user : list)
                {
                    setUserDict(user);
                }
            }
        }
        renderSuccess(rsp);
    }
    
    private static void setUserDict(User u)
    {
        u.setUserTypeName(DictUtils.getDictName(IDictType.USER_TYPE_DICTTYPE, u.getUserType()));
        u.setSexName(DictUtils.getDictName(IDictType.SEX_NAME_DICTTYPE, u.getSex()));
    }
    
    /**
     * 创建会员
     */
    public static void createVip()
    {
        CreateVipReq req = readObject(CreateVipReq.class);
        
        VIPInfo info = req.getInfo();
        
        long count = VIPInfo.count("vipName=?", info.getVipName());
        
        if (count > 0)
        {
            throw new ServiceException(IUserResultCode.CREATE_FAIL_USER_REPEAT);
        }
        
        String vid = UUIDGenerator.generate();
        info.setBalance(0D);
        info.setLevel(1);
        info.setVipId(vid);
        info.setCreateTime(new Timestamp(new Date().getTime()));
        info.save();
        CreateVipRsp rsp = new CreateVipRsp();
        rsp.setVipId(vid);
        renderSuccess(rsp);
    }
    
    /**
     * 获取会员列表
     */
    public static void getMemberList()
    {
        GetMemberListReq req = readObject(GetMemberListReq.class);
        GetMemberListRsp rsp = new GetMemberListRsp();
        rsp.setTotalNum(ServiceUtils.queryCountByCondition(req));
        if (rsp.getTotalNum() > 0)
        {
            List<VIPInfo> list = (ServiceUtils.queryByCondition(req,
                VIPInfo.class,
                "vipId",
                "vipName",
                "realName",
                "age",
                "phoneNumber",
                "sex",
                "balance",
                "createTime",
                "level"));
            if (CollectionUtils.isNotEmpty(list))
            {
                for (VIPInfo vipInfo : list)
                {
                    setVipConstant(vipInfo);
                }
                rsp.setInfoList(list);
            }
        }
        renderSuccess(rsp);
    }
    
    private static void setVipConstant(VIPInfo info)
    {
        info.setSexName(DictUtils.getDictName(IConstant.IDictType.SEX_NAME_DICTTYPE, info.getSex()));
        info.setLevelName((DictUtils.getDictName(IConstant.IDictType.LEVEL_NAME_DICTTYPE,
            String.valueOf(info.getLevel()))));
    }
}
